<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Requests\System\Menu\StoreRequest;
use App\Http\Requests\System\Menu\UpdateRequest;
use App\Http\Resources\System\Menu\IndexResource;
use App\Http\Resources\System\Menu\InfoResource;
use App\Models\System\Menu;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\QueryBuilder\QueryBuilder;

class MenuController extends Controller
{
    public function tree(Request $request): JsonResponse
    {
        $list = Menu::getMenus($request->user(), ['id', 'title', 'p_id']);
        array_unshift($list, [
            'id' => 0,
            'title' => '顶级菜单',
            'p_id' => 0,
        ]);

        return $this->success([
            'list' => $list,
        ]);
    }

    public function index(Request $request): JsonResponse
    {
        $query = Menu::query();
        $list = QueryBuilder::for($query, $request)
            ->allowedFilters(['title', 'code', 'type', 'id'])
            ->get();

        return $this->success(IndexResource::collection($list));
    }

    public function show(Menu $menu): JsonResponse
    {
        return $this->success(new InfoResource($menu));
    }

    public function store(StoreRequest $request): JsonResponse
    {
        $data = $request->validated();
        $row = new Menu($data);
        $row->save();

        return $this->success([], '添加成功');
    }

    public function update(Menu $menu, UpdateRequest $request): JsonResponse
    {
        $data = $request->validated();
        $menu->fill($data);
        $menu->save();

        return $this->success([], '更新成功');
    }

    public function destroy(Menu $menu): JsonResponse
    {
        $menu->delete();

        return $this->success([], '删除成功');
    }
}
